package com.ruc.deke.controller;

import java.util.ArrayList;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruc.deke.dao.DBCourseDAO;
import com.ruc.deke.dao.TeacherDAO;
import com.ruc.deke.dao.UserDAO;
import com.ruc.deke.model.DBRecord;
import com.ruc.deke.model.Teacher;
import com.ruc.deke.model.User;
import com.ruc.deke.utils.ParseUtil;

/**
 * 用于操作用户的行为
 * 
 * @author: cyj
 * @date: 2017年3月30日 上午10:50:22
 */

@Controller
@RequestMapping(value = "/user")
public class UserController {

	@Resource(name = "userDAOImpl")
	private UserDAO userDAO;

	@Resource(name = "teacherDAOImpl")
	private TeacherDAO teacherDAO;

	@Resource(name = "dbCourseDAOImpl")
	private DBCourseDAO dbCourseDAO;

	/**
	 * 用户注册
	 * 
	 * @param user
	 *            客户端传来的user信息
	 * @return
	 */
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	@ResponseBody
	public Object register(User user) {
		ArrayList<DBRecord> list = new ArrayList<DBRecord>();
		list = userDAO.getUserByName(user.getName());
		if (list.size() > 0) {
			return ParseUtil.toObject("existed");
		} else {
			userDAO.addUser(user);
			return ParseUtil.toObject("success");
		}
	}

	/**
	 * 用户id查询（学生）
	 * 
	 * @param user
	 * @return
	 * @author: zjh
	 * @date: 2017年9月24日
	 */
	@RequestMapping(value = "/askid", method = RequestMethod.POST)
	@ResponseBody
	public Object askid(User user) {
		String info = "";
		ArrayList<DBRecord> list = new ArrayList<DBRecord>();
		list = userDAO.getUserByName(user.getName());
		if (list.size() > 0) {
			int userId = list.get(0).getInt("USERID");
			return ParseUtil.toObject(new Integer(userId).toString());
		} else {
			info = "user_not_exist";
			return ParseUtil.toObject(info);
		}

	}

	/**
	 * 用户登录（学生）
	 * 
	 * @param user
	 * @return
	 * @author: cyj
	 * @date: 2017年3月30日 下午3:37:58
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public Object login(HttpSession session, User user) {

		String info = "";
		ArrayList<DBRecord> list = new ArrayList<DBRecord>();
		list = userDAO.getUserByName(user.getName());
		if (list.size() > 0) {
			String passwd = list.get(0).getString("PASSWD");
			int userId = list.get(0).getInt("USERID");
			int status = list.get(0).getInt("STATUS");
			if (user.getPasswd().equals(passwd)) {
				if (status == 1) {
					info = "success";
					session.setAttribute("name", user.getName());
					session.setAttribute("userid", userId);
					session.setAttribute("character", "student");
				} else {
					info = status == 0 ? "waiting" : "rejected";
				}

			} else {
				info = "passwd_err";
			}
		} else {
			info = "user_not_exist";
		}
		return ParseUtil.toObject(info);
	}

	/**
	 * 用户登录（老师）
	 * 
	 * @param user
	 * @return
	 * @author: cyj
	 * @date: 2017年3月30日 下午3:37:58
	 */
	@RequestMapping(value = "/tlogin", method = RequestMethod.POST)
	@ResponseBody
	public Object tlogin(HttpSession session, Teacher teacher) {
		String info = "";
		ArrayList<DBRecord> list = new ArrayList<DBRecord>();
		list = teacherDAO.getTeacherByTId(teacher.getTeacherid());
		if (list.size() > 0) {
			String passwd = list.get(0).getString("PASSWD");
			if (teacher.getPasswd().equals(passwd)) {
				info = "success";
				session.setAttribute("teacherid", teacher.getTeacherid());
				session.setAttribute("name", list.get(0).getString("TNAME"));
				session.setAttribute("character", "teacher");
				session.setAttribute("ano", list.get(0).getString("ANO"));
			} else {
				info = "passwd_err";
			}
		} else {
			info = "user_not_exist";
		}
		return ParseUtil.toObject(info);
	}

	/**
	 * 退出系统
	 * 
	 * @param session
	 *            Session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/logout")
	public String logout(HttpSession session) throws Exception {
		// 清除Session
		session.invalidate();

		return "redirect:/";
	}

	/**
	 * 退出系统
	 * 
	 * @param session
	 *            Session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/tlogout")
	public String tlogout(HttpSession session) throws Exception {
		// 清除Session
		session.invalidate();

		return "redirect:/views/tlogin.html";
	}

	/**
	 * 获取session信息
	 * 
	 * @param session
	 *            Session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getSession")
	@ResponseBody
	public Object getSession(HttpSession session) throws Exception {
		// 清除Session
		String info = "";
		info = session.getAttribute("character") == null ? "nlogin" : session.getAttribute("name").toString();
		return ParseUtil.toObject(info);
	}

	/**
	 * 获取用户的每一个module的状态
	 * 
	 * @param userId
	 * @param moduleId
	 * @return
	 * @author: cyj
	 * @date: 2017年4月1日 下午1:07:07
	 */
	@RequestMapping(value = "/getUserExpStatusByUserIdAndModuleID")
	@ResponseBody
	public ArrayList<DBRecord> getUserExpStatusByUserIdAndModuleID(HttpSession session, int moduleId) {
		int userId = Integer.parseInt(session.getAttribute("userid").toString());
		ArrayList<DBRecord> records = new ArrayList<DBRecord>();
		records = userDAO.getUserExpStatusByUserIdAndModuleID(userId, moduleId);
		return records;
	}
	
	/**
	 * 获取用户的每一个paper的状态
	 * 
	 * @param userId
	 * @param paperId
	 * @return
	 * @author: cyj
	 * @date: 2017年4月1日 下午1:07:07
	 */
	@RequestMapping(value = "/getUserExpStatusByPaper")
	@ResponseBody
	
	public ArrayList<DBRecord> getUserExpStatusByPaper(HttpSession session, @RequestParam(value = "paperId") String paperId) {
		int userId = Integer.parseInt(session.getAttribute("userid").toString());
		ArrayList<DBRecord> records = new ArrayList<DBRecord>();
		records = userDAO.getUserExpStatusByUserIdAndPaperId(userId, paperId);
		return records;
	}

	/**
	 * 获取某学校专业班级的一批学生（某位老师负责）
	 * 
	 * @param session
	 * @return
	 * @author: cyj
	 * @date: 2017年4月1日 下午3:51:45
	 */
	@RequestMapping(value = "/getUsersByAno")
	@ResponseBody
	public ArrayList<DBRecord> getUsersByAno(HttpSession session) {
		String ano = session.getAttribute("ano").toString();
		ArrayList<DBRecord> records = new ArrayList<DBRecord>();
		records = userDAO.getUsersByAno(ano);
		return records;
	}

	/**
	 * 更新用户的认证状态
	 * 
	 * @param userId
	 *            学生id
	 * @param status
	 *            0 未认证（默认） 1：认证
	 * @return
	 * @author: cyj
	 * @date: 2017年4月1日 下午4:29:15
	 */
	@RequestMapping(value = "/updateUsersStatus")
	@ResponseBody
	public Object updateUsersStatus(@RequestParam(value = "userId") int userId,
			@RequestParam(value = "status") int status) {
		DBRecord newRecord = new DBRecord();
		newRecord.setField("status", "" + status);
		DBRecord conditions = new DBRecord();
		conditions.setField("userid", "" + userId);
		String result = userDAO.updateUser(newRecord, conditions);
		return ParseUtil.toObject(result);
	}
	
	@RequestMapping(value = "/deleteUser")
	@ResponseBody
	public Object deleteUser(@RequestParam(value = "userId") int userId) {
		String result = userDAO.delUser(userId);
		return ParseUtil.toObject(result);
	}
	/**
	 * 获取某一ano群体的成绩
	 * 
	 * @param userId
	 * @param status
	 * @return
	 * @author: cyj
	 * @date: 2017年4月1日 下午5:15:20
	 */
	@RequestMapping(value = "/getUserScoresByModuleIdAndAno")
	@ResponseBody
	public Object getUserScoresByModuleIdAndAno(HttpSession session, @RequestParam(value = "moduleId") int moduleId) {
		ArrayList<DBRecord> scores = new ArrayList<DBRecord>();
		scores = userDAO.getUserScoresByModuleIdAndAno(session.getAttribute("ano").toString(), moduleId);
		return scores;
	}

	/**
	 * 获取ano范围内做了moduleid模块的学生信息
	 * 
	 * @param session
	 * @param moduleId
	 * @return
	 * @author: cyj
	 * @date: 2017年4月1日 下午9:45:29
	 */
	@RequestMapping(value = "/getUsersByModuleIdAndAno")
	@ResponseBody
	public Object getUsersByModuleIdAndAno(HttpSession session, @RequestParam(value = "moduleId") int moduleId) {
		ArrayList<DBRecord> scores = new ArrayList<DBRecord>();
		scores = userDAO.getUsersByModuleIdAndAno(session.getAttribute("ano").toString(), moduleId);
		return scores;
	}

	/**
	 * 获取学校代码及名称
	 * 
	 * @return
	 * @author: cyj
	 * @date: 2017年4月4日 上午10:33:17
	 */
	@RequestMapping(value = "/getUniversities")
	@ResponseBody
	public ArrayList<DBRecord> getUniversities() {
		ArrayList<DBRecord> universities = new ArrayList<DBRecord>();
		universities = dbCourseDAO.getUniversities();
		return universities;
	}

	/**
	 * 获取专业名称及代码
	 * 
	 * @return
	 * @author: cyj
	 * @date: 2017年4月4日 上午10:32:57
	 */
	@RequestMapping(value = "/getMajors")
	@ResponseBody
	public ArrayList<DBRecord> getMajors() {
		ArrayList<DBRecord> majors = new ArrayList<DBRecord>();
		majors = dbCourseDAO.getMajors();
		return majors;
	}

	/**
	 * 重置密码
	 * 
	 * @return
	 * @author zzh
	 * @date 2017年4月6日 下午03:58:00
	 */
	public void resetPassword() {

	}
}
